//
//  DDropLineTableViewCell.swift
//  Drop
//
//  Created by hushaohua on 2018/2/23.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

class DDropLineTableViewCell: UITableViewCell {
    
    static let normalReuseId:String = "normal";
    static let doingReuseId:String = "doing";//doing{no tag,duration, dash}
    static let lastReuseId:String = "last";//doing
    static let lastDoingReuseId:String = "last-doing"
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier);
        self.contentView.addSubview(self.lineView);
        if (reuseIdentifier! == DDropLineTableViewCell.normalReuseId){
            self.contentView.addSubview(self.getBeginDateLabel());
            self.contentView.addSubview(self.getTitleLabel());
        }else if (reuseIdentifier! == DDropLineTableViewCell.doingReuseId){
            self.contentView.addSubview(self.getBeginDateLabel());
            self.configLineForDoing();
        }else if (reuseIdentifier! == DDropLineTableViewCell.lastReuseId){
            self.contentView.addSubview(self.getTitleLabel());
        }else if (reuseIdentifier! == DDropLineTableViewCell.lastDoingReuseId){
            self.configLineForDoing();
        }
        UIMenuController.shared.menuItems = self.menuItems;
//        self.addSubviewConstraints();
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    lazy var lineView:UIView = {
        var view:UIView = UIView(frame: .zero);
        view.translatesAutoresizingMaskIntoConstraints = false;
        view.backgroundColor = UIColor.darkGray;
        return view;
    }();
    
    func configLineForDoing() -> Void{
        self.lineView.backgroundColor = UIColor.clear;
        for index in 0..<3 {
            let layer = self.dotLayer(CGRect(x:0,y:(4 + index * 10),width:6,height:6));
            self.lineView.layer.addSublayer(layer);
            self.lineDots.append(layer);
        }
        self.lineView.layer.addSublayer(self.dotLayer(CGRect(x:0,y:34,width:6,height:10)));
    }
    
    lazy var lineDots:[CALayer] = {
        return [CALayer]();
    }();
    
    func dotLayer(_ frame:CGRect) -> CALayer{
        let layer:CALayer = CALayer();
        layer.backgroundColor = UIColor.darkGray.cgColor;
        layer.frame = frame;
        return layer;
    }
    
    func stopBright() -> Void{
        for index in 0..<self.lineDots.count {
            let layer = self.lineDots[index];
            layer.removeAllAnimations();
        }
    }
    func startBright() -> Void{
        for index in 0..<self.lineDots.count {
            let layer = self.lineDots[index];
            layer.removeAllAnimations();
            let anim = CABasicAnimation(keyPath: "opacity");
            anim.fromValue = 1;
            anim.toValue = 0;
            anim.duration = 1;
            anim.repeatCount = MAXFLOAT;
            anim.autoreverses = true;
            anim.beginTime = CACurrentMediaTime() + TimeInterval(self.lineDots.count - index) * 0.5;
            layer.add(anim, forKey: "fade\(index)");
        }
    }
    
    var shouldModifyTag:((UITableViewCell)->(Bool))?;
    var shouldRevoke:((UITableViewCell)->(Bool))?;
    var shouldNote:((UITableViewCell)->(Bool))?;
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        let string:String = NSStringFromSelector(action) as String;
        if (string == "customRevokeAction" && self.shouldRevoke != nil){
            return self.shouldRevoke!(self);
        }else if (string == "customModifyTagAction" && self.shouldModifyTag != nil){
            return self.shouldModifyTag!(self);
        }else if (string == "updateNoteAction" && self.shouldNote != nil){
            return self.shouldNote!(self);
        }
        return false;
    }

    
    lazy var menuItems:[UIMenuItem] = {
        var items:[UIMenuItem] = [UIMenuItem]();
        let revokeItem:UIMenuItem = UIMenuItem(title: "Revoke", action: #selector(customRevokeAction));
        items.append(revokeItem);
        let modifyItem:UIMenuItem = UIMenuItem(title: "Change", action: #selector(customModifyTagAction));
        items.append(modifyItem);
        let noteItem:UIMenuItem = UIMenuItem(title: "Note", action: #selector(updateNoteAction));
        items.append(noteItem);
        return items;
    }();

    var customRevokeClosure:((UITableViewCell) -> Void)?;
    @objc func customRevokeAction() -> Void{
        if (self.customRevokeClosure != nil){
            self.customRevokeClosure!(self);
        }
    }
    var customModifyTagClosure:((UITableViewCell) -> Void)?;
    @objc func customModifyTagAction() -> Void{
        if (self.customModifyTagClosure != nil){
            self.customModifyTagClosure!(self);
        }
    }
    var updateNoteClosure:((UITableViewCell) -> Void)?;
    @objc func updateNoteAction() -> Void{
        if (self.updateNoteClosure != nil){
            self.updateNoteClosure!(self);
        }
    }
    var tapTitleClosure:((UITableViewCell) -> Void)?;
    @objc func tapTitle() {
        if (self.tapTitleClosure != nil){
            self.tapTitleClosure!(self);
        }
    }
    
    var beginDateLabel:UILabel?;
    func getBeginDateLabel() -> UILabel{
        if (beginDateLabel == nil){
            let label:UILabel = UILabel(frame: .zero);
            label.translatesAutoresizingMaskIntoConstraints = false;
            label.textColor = UIColor.gray;
            label.font = UIFont.systemFont(ofSize: 16, weight: .medium);
            label.textAlignment = .left;
            self.beginDateLabel = label;
        }
        return self.beginDateLabel!;
    };

    var titleLabel:UILabel?
    func getTitleLabel() -> UILabel{
        if (titleLabel == nil){
            let label:UILabel = UILabel(frame: .zero);
            label.translatesAutoresizingMaskIntoConstraints = false;
            label.textColor = UIColor.darkGray;
            label.backgroundColor = UIColor(white:0.95,alpha:0.9);
            label.font = UIFont.systemFont(ofSize: 14, weight: .light);
            label.textAlignment = .center;
            label.numberOfLines = 2;
            self.titleLabel = label;
            let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapTitle));
            label.isUserInteractionEnabled = true;
            label.addGestureRecognizer(tap);
        }
        return self.titleLabel!;
    };
    
    func addSubviewConstraints() -> Void{
        var views:[String : UIView] = ["line" : self.lineView];
        //"time" : self.beginDateLabel, "title" : self.titleLabel,
        var costraints = [NSLayoutConstraint]();
        if (beginDateLabel != nil){
            views["time"] = self.beginDateLabel;
            costraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[time(==time_height)]-0-|", options: [], metrics: ["time_height" : 22], views: views);
            costraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-margin-[time]-|", options: .directionLeadingToTrailing, metrics: ["margin" : 42 + self.marginLeftOffset], views: views);
        }
        if (titleLabel != nil){
            views["title"] = self.titleLabel;
            costraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[title(==title_height)]", options: [.directionLeadingToTrailing], metrics: ["title_height" : 42], views: views);
            costraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[line]-0-[title]-right-|", options: .directionLeadingToTrailing, metrics: ["right" : 20], views: views);
        }
        
        costraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[line(==line_height)]", options: [.directionLeadingToTrailing], metrics: ["line_height" : 44], views: views);
        
        costraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[line(6)]", options: .directionLeadingToTrailing, metrics: ["left" : 60 + self.marginLeftOffset], views: views);
        self.contentView.addConstraints(costraints);
    }
    
    var marginLeftOffset:CGFloat = 22{
        didSet{
            if (self.contentView.constraints.count == 0){
                self.addSubviewConstraints();
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
